




//
//  ZLearnSubViewController.m
//  ZQLearn
//
//  Created by admin on 2019/4/18.
//  Copyright © 2019 admin. All rights reserved.

#import "ZLearnSubViewController.h"
#import "ReadCollectionViewCell.h"
#import "ReadModel.h"
#import "ZBookMsgDetailVC.h"
#import "HomeModel.h"
@interface ZLearnSubViewController ()<ZJScrollPageViewDelegate,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

@property(nonatomic,strong)UICollectionView *collectionView;

@property(nonatomic,copy)NSString *currentIndexId;

@property(nonatomic,strong)NSMutableArray *datasArray;


@property(nonatomic,assign)NSInteger currentPage;

@end

#define kLineNumber 3
#define kBarHeight 40

///这个cellid 全局不能重复
NSString *const cellid = @"read";

//#define cellid = @"store"


@implementation ZLearnSubViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
     [self.navigationItem setItemWithTitle:@"读书" textColor:kNavigationTitleColor fontSize:18 itemType:center];
//    self.currentIndexId = 0;
    self.currentPage = 1;
    self.datasArray = [NSMutableArray array];
    [self.view addSubview:self.collectionView];
    
//    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(jjjj:) name:@"jj" object:nil];
    // Do any additional setup after loading the view.
}


//流式布局
- (UICollectionViewFlowLayout *)flowLayout {
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    //整个 section 的四周边界的margin
    layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    ///45行代码和  ScreenWidth-4（minimumLineSpacing*2）形成中间的小横线
    layout.minimumLineSpacing = 1.f;
    layout.minimumInteritemSpacing = 0.f;
    //    layout.headerReferenceSize = CGSizeMake(kScreenWidth, SectionHeaderHeight);
    layout.itemSize = CGSizeMake((ScreenWidth-2)/3, ScreenWidth>375?205:185);
    return layout;
}
- (UICollectionView *)collectionView {
    if (!_collectionView) {
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight-kTabHeight-ScreenHeightFlex-kBarHeight) collectionViewLayout:[self flowLayout]];
        
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.showsVerticalScrollIndicator = NO;
        [self registerCell];
        WeakStament(ws);
        _collectionView.mj_header = [CustomRefreshHeader headerWithRefreshingBlock:^{
            [ws refreshData];
        }];
        _collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            [ws loadMoreData];
        }];
        _collectionView.backgroundColor = kWhiteColor;
    }
    return _collectionView;
}

- (void)registerCell {
    
    [_collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([ReadCollectionViewCell class]) bundle:nil] forCellWithReuseIdentifier:cellid];
}



#pragma datasource


-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return self.datasArray.count;
}



-(__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    ReadCollectionViewCell *cell;
    
    if (self.datasArray.count>indexPath.row) {
        
        ReadModel *model = self.datasArray[indexPath.row];
        cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellid forIndexPath:indexPath];
        [cell.headImg sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",kPicServerUrl,model.bookInfo[@"photo"]]] placeholderImage:nil];
        cell.nameLab.text = model.bookInfo[@"name"];
    }
    
    return cell;
}


#pragma mark - delegate

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    ReadModel *model = self.datasArray[indexPath.row];
    ZBookMsgDetailVC *msg = [ZBookMsgDetailVC new];
    MidModel *MModel = [MidModel new];
    MModel.ID = model.ID;
    MModel.name = model.name;
    MModel.gradeName = model.outsideColumnInfo[@"name"];
    YYLog(@"%@",MModel.gradeName);
    MModel.price = model.price;
    MModel.isPaint = model.isPaint;
    MModel.catelogType = model.catelogType;
    YYLog(@"%@",model.catelogType);
    MModel.picUrl = [NSString stringWithFormat:@"%@%@",kPicServerUrl,model.bookInfo[@"photo"]];
    msg.MModel = MModel;
    [self.navigationController pushViewController:msg animated:YES];
}


#pragma mark ZJScrollPageViewChildVcDelegate
- (void)zj_viewWillAppearForIndex:(NSInteger)index{
    YYLog(@"%ld",index);
    [UserModel shareInstance].tabIndex = index;
//    self.currentIndexId = index;
}
- (void)zj_viewDidAppearForIndex:(NSInteger)index{
    
}
- (void)zj_viewWillDisappearForIndex:(NSInteger)index{
    
}
- (void)zj_viewDidDisappearForIndex:(NSInteger)index{
    
}
- (void)zj_viewDidLoadForIndex:(NSInteger)index{
    //这里具体处理请求逻辑不同的页面根据索引进行请求
    YYLog(@"%ld",index);
    //    self.currentIndex = index;
    //    [self loadDataWithIndex:index];
//    [self loadDataWithIndex:[UserModel shareInstance].tabIndex];
    [self loadDataWithIndex:index];
}

///根据索引直接进行数据请求
- (void)loadDataWithIndex:(NSInteger)index{

    if (self.dataArray.count>0) {
        ReadModel *model = self.dataArray[index];
        self.currentIndexId = model.ID;
        [self loadDataWithId:model.ID];
        YYLog(@"%@",model.ID);
       
    }
}

///数据请求
- (void)loadDataWithId:(NSString *)Id{
    
    if (self.currentPage==1) {
        [self.datasArray removeAllObjects];
    }
    
    NSDictionary *dic = @{@"outsideColumnInfo.id":Id,@"pageIndex":@(self.currentPage),@"pageSize":@(15),@"outsideType":@"1",};
    WeakStament(ws);
    [ZNetworkService getRequestWithBaseUrl:kReadBookListUrl setParameters:dic success:^(id result) {
        
        YYLog(@"%@",result);
        if ([result[@"errorCode"]integerValue]==0) {
            NSArray *arr = result[@"result"];
            for (NSDictionary *dic in arr) {
                ReadModel *model = [ReadModel mj_objectWithKeyValues:dic];
                model.price = model.bookInfo[@"price"];
                model.isPaint = model.bookInfo[@"isPaint"];
                model.ID = model.bookInfo[@"id"];
                model.catelogType = model.bookInfo[@"catelogType"];
//                model.name = model.outsideColumnInfo[@"name"];
                
                [self.datasArray addObject:model];
            }
            [ws.collectionView reloadData];
            [ws endRefresh];
            
            
            //这个放的位置很重要  加载更多没有数据处理
            if (arr.count==0) {
                [ws noMoreData];
            }
        }else{
            [AFToast showText:result[@"errorMsg"]];
            [self endRefresh];
        }
        
    } fail:^(NSError *error) {
        
        YYLog(@"%@",error);
        [self endRefresh];
        
    } delegater:nil];
}

///
- (void)refreshData{
    self.currentPage=1;
    self.currentIndexId = [UserModel shareInstance].Id;
    [self loadDataWithId:self.currentIndexId];
}

- (void)loadMoreData{
    self.currentPage++;
    self.currentIndexId = [UserModel shareInstance].Id;
    [self loadDataWithId:self.currentIndexId];
}


- (void)endRefresh{
    [self.collectionView.mj_header endRefreshing];
    [self.collectionView.mj_footer endRefreshing];
}


///没有更多数据
- (void)noMoreData {
    [self.collectionView reloadData];
    [self.collectionView.mj_footer endRefreshingWithNoMoreData];
}


@end
